import {ActionType, PageContainer, ProColumns, ProTable,} from '@ant-design/pro-components';
import {Access, FormattedMessage, useAccess, useIntl} from '@umijs/max';
import {Button, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import JsonView from '@uiw/react-json-view';
import CreateUpdateForm from "./components/CreateUpdateForm";
import {PlusOutlined} from "@ant-design/icons";
import {switchMetas} from "@/services/switch-meta/api";


const TableList: React.FC = () => {
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.SwitchMetaItem>();
  const actionRef = useRef<ActionType | null>(null);
  const access = useAccess() as Record<string, boolean>;

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  const fetchSwitchMetaList = async (params: any, sort: any, filter: any) => {
    try {
      const result = await switchMetas(params, sort, filter);
      return {
        ...result,
        success: true,
      };
    } catch (error: any) {
      console.error('ProTable request error:', error);
      messageApi.error(error.data?.message || '列表加载失败，请重试');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const columns: ProColumns<API.SwitchMetaItem>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.namespace.searchTable.id"
          defaultMessage="ID"
        />
      ),
      dataIndex: 'id',
      width: 80,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.factor"
          defaultMessage="因子"
        />
      ),
      dataIndex: 'factor',
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.factorAlias"
          defaultMessage="别名"
        />
      ),
      dataIndex: 'alias',
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.description"
          defaultMessage="因子描述"
        />
      ),
      dataIndex: 'description',
      width: 150,
      valueType: 'textarea',
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.namespaceBind"
          defaultMessage="命名空间"
        />
      ),
      dataIndex: 'namespaceId',
      hideInForm: true,
      hideInSearch: true,
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.createBy"
          defaultMessage="创建人"
        />
      ),
      dataIndex: 'createdBy',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.createTime"
          defaultMessage="创建时间"
        />
      ),
      sorter: true,
      hideInForm: true,
      width: 170,
      dataIndex: 'createTime',
      key: 'updatedAt',
      valueType: 'dateTimeRange',
      render: (_, record) => {
        if (!record.createTime) return '-';
        return record.createTime.replace('T', ' ').substring(0, 19);
      },
      fieldProps: {
        style: {
          width: '360px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.updateBy"
          defaultMessage="修改人"
        />
      ),
      dataIndex: 'updateBy',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      width: 150,
      fieldProps: {
        style: {
          width: '150px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.updateTime"
          defaultMessage="修改时间"
        />
      ),
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      width: 170,
      dataIndex: 'updateTime',
      render: (_, record) => {
        if (!record.createTime) return '-';
        return record.createTime.replace('T', ' ').substring(0, 19);
      },
      fieldProps: {
        style: {
          width: '360px',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.system.titleOption"
          defaultMessage="操作"
        />
      ),
      dataIndex: 'option',
      valueType: 'option',
      width: 170,
      render: (_, record) => [
        <Access accessible={!access['switches-meta:edit']}>
          <CreateUpdateForm
            isCreate={false}
            readOnly={record.namespaceId === 0}
            trigger={
              <a>
                <FormattedMessage
                  id={record.namespaceId === 0 ? "pages.switch-meta.searchTable.view" : "pages.switch-meta.searchTable.edit"}
                  defaultMessage={record.namespaceId === 0 ? "查看" : "编辑"}
                />
              </a>
            }
            key="edit"
            reload={() => actionRef.current?.reload()}
            values={record}
          />
        </Access>
      ],
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.SwitchMetaItem, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.switch-meta.searchTable.title',
          defaultMessage: '元信息列表',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: {
            xs: 24,
            sm: 12,
            md: 8,
            lg: 8,
            xl: 6,
            xxl: 6,
          },
        }}
        toolBarRender={() => [
          <Access accessible={!access['switches-meta:create']}>
            <CreateUpdateForm
              isCreate={true}
              trigger={
                (
                  <Button type={'primary'} icon={<PlusOutlined/>}>
                    <FormattedMessage
                      id="pages.switch-meta.searchTable.createIcon"
                      defaultMessage="新建"/>
                  </Button>
                )
              }
              key="create"
              reload={() => actionRef.current?.reload()}
            />
          </Access>
        ]}
        request={fetchSwitchMetaList}
        columns={columns}
      />

      {showDetail && (
        <Modal
          title="元信息详情"
          open={showDetail}
          onCancel={() => setShowDetail(false)}
          footer={null}
          width={800}
          centered
          destroyOnHidden={true}
        >
          <JsonView
            value={{
              ...currentRow,
              json_schema: currentRow?.jsonSchema ? (() => {
                try {
                  return JSON.parse(currentRow.jsonSchema);
                } catch (e) {
                  return currentRow.jsonSchema;
                }
              })() : undefined
            }}
            style={{
              backgroundColor: '#f6f8fa',
              padding: '16px',
              borderRadius: '6px'
            }}
            collapsed={false}
          />
        </Modal>
      )}

    </PageContainer>
  );
};

export default TableList;

